canvas - 无法使用重复模式在画布上重复图像
问题描述
我正在尝试使用我自己创建的图形在画布上创建一个简单的重复图像。不幸的是 createPattern(img, repeat) 导致只有一个版本的图像被重复。我尝试将其保存为图像,然后使用 img.src 加载该图像,我还尝试创建第二个画布并尝试使用第一个画布作为模式的基础在该画布上绘制,但两者都产生相同结果 - 只是图像的一个版本。我在这里想念什么?
这是我的代码的两个版本:
使用两个画布:
function draw() {
var canvas1 = document.getElementById('drawcanvas')
var ctx = canvas1.getContext('2d');
var canvas2 = document.getElementById('canvas');
var ctx2 = canvas2.getContext('2d');
ctx.fillStyle = '#f5f2d0';
ctx.fillRect(0, 0, 205, 255);
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, 200, 250);
ctx.fillStyle = '#77d499';
ctx.fillRect(5, 5, 195, 245);
var img = new Image();
img.addEventListener('load', function() {
ctx.drawImage(img, 48.75, 20, 100, 200)
}, false)
img.src = 'Images/wine-icon-15966.png';
var pattern = ctx2.createPattern(canvas, 'repeat');
ctx2.fillStyle = pattern;
ctx.fillRect(0, 0, 2480, 3508);
}
使用单独的图像:
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = '#f5f2d0';
ctx.fillRect(0, 0, 2480, 3508);
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, 200, 250);
ctx.fillStyle = '#77d499';
ctx.fillRect(5, 5, 195, 245);
var img = new Image();
img.addEventListener('load', function() {
ctx.drawImage(img, 48.75, 20, 100, 200)
}, false)
img.src = 'Images/wine-icon-15966.png';
}
谢谢你的帮助!
解决方案
我做了一些调整,并使用从画布绘制选项使其工作。如建议的那样,我将逻辑移到了 load 语句中。我还在 createPattern 中提到了画布,它是第二个画布的 id,而不是我给第一个画布 (drawcanvas) 的 id,这意味着我本质上是在空白画布上绘制一个空白画布。这是我更新的代码。
function draw() {
var canvas1 = document.getElementById('drawcanvas')
var ctx = canvas1.getContext('2d');
var canvas2 = document.getElementById('canvas');
var ctx2 = canvas2.getContext('2d');
ctx.fillStyle = '#f5f2d0';
ctx.fillRect(0, 0, 205, 255);
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, 200, 250);
ctx.fillStyle = '#77d499';
ctx.fillRect(5, 5, 195, 245);
var img = new Image();
img.src = 'Images/wine-icon-15966.png';
img.addEventListener('load', function() {
ctx.drawImage(img, 48.75, 20, 100, 200);
var pattern = ctx2.createPattern(drawcanvas, 'repeat');
ctx2.fillStyle = pattern;
ctx2.fillRect(0, 0, canvas.width, canvas.height);
ctx2.fill();
}, false);
ctx2.fillStyle = '#f5f2d0';
ctx2.fillRect(0, 0, canvas.width, canvas.height);
}
推荐阅读
- python - 分离子进程以继续执行程序
- python - 使用 Python 以纳秒为单位计算时间过程
- asp.net - 寻呼机更小且无边界
- java - OrientDB 3.0.0 创建嵌入式给出 java.lang.NullPointerException
- android - 输入类型文件不适用于 Android 6
- django - 删除字符串列表周围的双引号
- java - Spring thymleaf 如何从 jquery 数据表中添加 th:href="@{}"
- java - 读取 .csv 文件(系统找不到指定的文件)
- html - 在部门菜单的悬停上闪烁我想创建下拉菜单
- angular - 尝试启动 Angular 项目时出错