javascript - 在Javascript中将图案绘制到矩形
问题描述
正如标题所说,我正在尝试将图案绘制到矩形上。我创建了一个矩形构造函数来绘制多个矩形,然后将它们存储在一个数组中,以便循环调用该createRect()
函数。
问题是,画布最终完全变黑了。
var canvas = document.getElementById("slideshow");
var ctx = canvas.getContext("2d");
var img = [];
var img_height = 380;
var img_length = 475.75;
function picture(){
this.img_height = img_height;
this.img_length = img_length;
this.X = 0;
this.getX = function(num) {
switch(num){
case 1:
break;
case 2:
this.X = this.img_length;
break;
case 3:
this.X = this.img_length * 2;
break;
case 4:
this.X = this.img_length * 3;
break;
case 5:
this.X = -this.img_length;
break;
};
};
this.createRect = function(num){
this.obj = document.getElementById('p' + num);
this.pattern = ctx.createPattern(this.obj, 'no-repeat');
ctx.fillStyle = this.pattern;
ctx.beginPath();
ctx.fillRect(this.X, 0, this.img_length,this.img_height);
ctx.fill();
}
};
这些是创建每个对象并显示它们的循环。
//Create objects
for(let i = 0;i<=5;i++)
{
img[i-1] = new picture();
}
//get x coords and display
for(let i = 0;i<5;i++)
{
img[i].getX(i+1);
img[i].createRect(i+1);
}
解决方案
我发明了一个类 _Rect 来使用createRect()
你所拥有的方法。此示例不适用于 SO,但您可以在codepen上看到一个工作示例
请确保您使用的是来自同一域的图像。
let ctx = canvas.getContext("2d")
class _Rect{
constructor(o){
this.X = o.x;
this.y = o.y;
this.img_length = o.w;
this.img_height = o.h
}
createRect() {
this.object = document.getElementById('p1');
this.pattern = ctx.createPattern(this.object, 'no-repeat');
ctx.fillStyle = this.pattern;
ctx.beginPath();
ctx.fillRect(this.X, 0, this.img_length, this.img_height);
ctx.strokeRect(this.X, 0, this.img_length, this.img_height);
};
}
canvas{border:1px solid}
<canvas id="canvas" width="300" height="300"></canvas>
<img id="p1" src="pin.png" />
推荐阅读
- html - 为什么我的 Django 表单在没有提交数据的情况下返回 QueryDict?
- google-cloud-platform - 适用于 Google 域的具有 Cloud DNS 的 GSuite 电子邮件
- php - 通过引用传递的错误控制运算符
- machine-learning - CUDA在学习过程中的问题
- rust - 如何将源文件打包成一个文件?
- python - 使用python解析json文件并计算每个对象下的项目数
- python - 如何设置 Flask-SQLAlchemy 在启动时优雅地管理 PostgreSQL 不可用
- sql - 如何在主要描述列中包含父描述?
- linux - bash检查多个目录中的输出(.txts)是否包含某些字符串
- kubernetes - Kubernetes 中的微服务服务发现