简体   繁体   English

createPattern无法在Canvas Rect上运行吗?

[英]createPattern not working on a Canvas Rect?

First off heres live code 首先是这里的现场代码

I want to fillStyle of a square with a image using canvas. 我想使用画布使用图像填充正方形。

I have 2 rectangles that I've created: 我创建了2个矩形:
在此处输入图片说明

Question: How do I apply an images as a pattern to the pink rotated and translated sq? 问题: 如何将图像作为图案应用到旋转和平移的粉红色正方形上?

using this JS: 使用此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();

});

You try to draw the image before it was loaded. 您尝试在加载图像之前绘制图像。 The script working flow is the following: 脚本工作流程如下:

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

then 然后

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

and then, when image load complete 然后,当图像加载完成时

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

See your CodePen updated 查看您的CodePen 更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM