填充

纯色

var cvs = document.getElementById("myCanvas"); 
var ctx = cvs.getContext("2d"); 
ctx.fillStyle = "#FF0000"; 
ctx.fillRect(0,0,150,75);

image.png

渐变填充

径向渐变

var cvs = document.getElementById('myCanvas')
var ctx = cvs.getContext("2d")
// 创建渐变1 - 45度径向渐变
var grd1 = ctx.createLinearGradient(0, 0, 100, 100);
grd1.addColorStop(0, 'red')
grd1.addColorStop(1, 'white')
// 创建渐变2 - 横向径向渐变
var grd2 = ctx.createLinearGradient(100, 100, 200, 100);
grd2.addColorStop(0, 'red')
grd2.addColorStop(1, 'white')

// 填充渐变1
ctx.fillStyle = grd1
ctx.fillRect(0, 0, 100, 100)
// 填充渐变2
ctx.fillStyle = grd2
ctx.fillRect(100, 100, 200, 200)

image.png

球型/放射渐变

var cvs = document.getElementById('myCanvas')
var ctx = cvs.getContext("2d")
// 创建渐变
var grd = ctx.createRadialGradient(100, 100, 0, 100, 100, 90);
grd.addColorStop(0, 'red')
grd.addColorStop(1, 'green')

// 填充渐变
ctx.fillStyle = grd
ctx.fillRect(0, 0, 200, 200)

image.png

图片填充

文档:https://www.w3school.com.cn/h...
方法1:

var cvs = document.getElementById('myCanvas')
var ctx = cvs.getContext("2d")
var img = new Image()
img.src = 'https://visualhunt.com/photos/1/milky-way-over-fence.jpg?s=l'
img.onload = function () {
  var pattern = ctx.createPattern(img, "no-repeat")
  ctx.fillStyle = pattern
  ctx.fillRect(10, 10, 780, 510) // 图片尺寸800x530
}

image.png
方法2:

document.getElementById('img_demo').onload = function () { // 前提:有id为img_demo的img
  var cvs = document.getElementById('myCanvas')
  var ctx = cvs.getContext("2d")
  ctx.drawImage(document.getElementById('img_demo'), 10, 10)
}

image.png

文字填充

var cvs = document.getElementById('myCanvasText')
var ctx = cvs.getContext("2d")
ctx.font = '25pt Arial'
ctx.fillStyle = 'cornflowerblue'
ctx.strokeStyle = 'blue'
ctx.fillText('Hello World!', 20, 50)
ctx.strokeText('Hello World!', 20, 50)

image.png

视频填充

var video = document.getElementById("video1");
var cvs = document.getElementById("myCanvasBgVideo");
ctx = cvs.getContext('2d');
video.addEventListener('play', function() {
  var i = window.setInterval( function() {
    ctx.drawImage(video, 5, 5, 270, 135)
  }, 10)
},false)
video.addEventListener('pause',function() {
  window.clearInterval(i)
}, false)
video.addEventListener('ended',function() {
  clearInterval(i)
}, false)

image.png

图形

直线

var cvs = document.getElementById('myCanvas')
var ctx = cvs.getContext("2d")
ctx.moveTo(10, 10)
ctx.lineTo(120, 150)
ctx.strokeStyle = '#FF0000'
ctx.stroke()

image.png

圆形

var cvs = document.getElementById('myCanvas')
var ctx = cvs.getContext("2d")
ctx.beginPath()
ctx.arc(100, 100, 30, 0, 2 * Math.PI)
ctx.strokeStyle = '#FF0000'
ctx.stroke()

image.png

圆弧

var cvs = document.getElementById('myCanvas')
var ctx = cvs.getContext("2d")
ctx.beginPath()
ctx.arc(100, 100, 30, 0, 0.5 * Math.PI)
ctx.strokeStyle = '#FF0000'
ctx.stroke()

image.png


davidshi
33 声望6 粉丝

Deliver Happiness


引用和评论

0 条评论