createPattern 不适用于 Canvas 矩形?

createPattern not working on a Canvas Rect?

首先在这里live code

我想使用 canvas 用图像填充正方形的样式。

我创建了 2 个矩形:

问题: 如何将图像作为图案应用到粉红色旋转和平移的正方形?

使用这个 JS:

$(document).ready(function(){
  var c = $('#myCanvas')[0],
      ctx = c.getContext('2d');

//starting square.
  ctx.translate(100,0);
  ctx.fillRect(100, 100, 100, 100);
  var gradient = ctx.createLinearGradient(0, 0, 0, c.width);
  gradient.addColorStop(0, "rgb(255, 255, 255)");
  gradient.addColorStop(1, "rgb(0, 0, 0)");
  ctx.save();

//next square
  ctx.translate(100,100);
  ctx.scale(2,2);
  ctx.rotate(Math.PI/4);
  var image = new Image();
  ctx.fillStyle = 'rgba(200,10,10,.5)';
//the image isnt being applied as a pattern to the sq?
  image.src = 'http://lorempixel.com/400/200/';

  $(image).load(function(){
    var pattern = ctx.createPattern(image, 'repeat');
    ctx.fillStyle = pattern;
  });

  ctx.fillRect(0,0,100,100);
  ctx.restore();

});

您尝试在图像加载之前绘制图像。脚本工作流程如下:

image.src = 'http://lorempixel.com/400/200/';

然后

ctx.fillRect(0,0,100,100);
ctx.restore();

然后,当图像加载完成时

var pattern = ctx.createPattern(image, 'repeat');
ctx.fillStyle = pattern;

查看您的 CodePen updated