怎么在网页中创建canvas和文字?

怎么在网页中创建canvas和文字?,第1张

<canvas id="t_con" height="200px" width="200px"></canvas>

<script>

var ele = document.getElementById("t_con")

var ctx = ele.getContext("2d")

// 字号为60px ,字体为impact

ctx.font = "30px impact"

//将文本填充为棕色

ctx.fillStyle = "#960"

//将文本设为居中对齐

ctx.textAlign = 'center' //规定变换 *** 控点的位置

//设置文字

ctx.fillText("Happy Trails!", 100, 55, 400)//参数为fillText(文本内容, 变换 *** 控点的x坐标, 变换中心的y坐标, 文本最大宽度)

</script>

1. [代码][HTML]代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

<html>

<head>

<title>write demo</title>

</head>

<body>

<canvas width="800" height="450" style="border:1px solid black"></canvas>

<div id="info">-</div>

<script>

var canvas = document.getElementsByTagName('canvas')[0]

canvas.addEventListener('mousemove', onMouseMove, false)

canvas.addEventListener('mousedown', onMouseDown, false)

canvas.addEventListener('mouseup', onMouseUp, false)

var info = document.getElementById('info')

var context = canvas.getContext('2d')

var linex = new Array()

var liney = new Array()

var linen = new Array()

var lastX = -1

var lastY = -1

var hue = 0

var flag = 0

function onMouseMove(evt) {

if (flag == 1) {

linex.push(evt.layerX)

liney.push(evt.layerY)

linen.push(1)

context.save()

context.translate(context.canvas.width/2, context.canvas.height/2)

context.translate(-context.canvas.width/2, -context.canvas.height/2)

context.beginPath()

context.lineWidth = 5 + Math.random() * 10

for (var i=1i<linex.lengthi++) {

lastX = linex[i]

lastY = liney[i]

if (linen[i] == 0) {

context.moveTo(lastX,lastY)

} else {

context.lineTo(lastX,lastY)

}

}

huehue = hue + 10 * Math.random()

context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)'

context.shadowColor = 'white'

context.shadowBlur = 10

context.stroke()

context.restore()

}

info.firstChild.nodeValue ='x = ' + evt.layerX + ' y = ' + evt.layerY

}

function onMouseDown(evt) {

flag = 1

linex.push(evt.layerX)

liney.push(evt.layerY)

linen.push(0)

}

function onMouseUp(evt) {

flag = 0

linex.push(evt.layerX)

liney.push(evt.layerY)

linen.push(0)

}

</script>

</body>

</html>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11698172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存