Javascript createPattern在画布矩形上不工作?

Javascript createPattern在画布矩形上不工作?,javascript,canvas,Javascript,Canvas,首先是这里 我想用画布上的图像填充正方形的样式 我创建了两个矩形: 问题: 如何将图像作为图案应用于旋转和平移的粉色sq? 使用此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 gra

首先是这里

我想用画布上的图像填充正方形的样式

我创建了两个矩形:

问题: 如何将图像作为图案应用于旋转和平移的粉色sq?

使用此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/';
然后

然后,当图像加载完成时

var pattern = ctx.createPattern(image, 'repeat');
ctx.fillStyle = pattern;
看到你的密码笔了吗

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