gpt4 book ai didi

javascript - createPattern 不适用于 Canvas 矩形?

转载 作者:行者123 更新时间:2023-12-03 10:46:48 25 4
gpt4 key购买 nike

首先是 live code

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

我创建了 2 个矩形:
enter image description here

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

使用这个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

关于javascript - createPattern 不适用于 Canvas 矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28549998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com