html - 用画布创建图案
问题描述
我想用画布创建一个pettern。应该使用的图片也应该首先生成。我已经用这段代码做了这样的事情:
document.addEventListener('DOMContentLoaded', function () {
async function draw() {
var canvas = document.getElementById('canvas1')
var ctx = canvas.getContext("2d");
var canvas = ctx.createImageData(500, 300);
ctx.fillStyle = "#7289DA";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Select the color of the stroke
ctx.strokeStyle = '#74037b';
// Draw a rectangle with the dimensions of the entire canvas
ctx.strokeRect(0, 0, canvas.width, canvas.height);
ctx.font = 'bold 70px sans-serif';
// Select the style that will be used to fill the text in
ctx.save();
ctx.rotate(1.7*Math.PI);
ctx.fillStyle = '#23272A';
ctx.fillText('Text', -70, 300);
ctx.restore();
// Actually fill the text with a solid color
}
draw();
});
<canvas id="canvas" width="1500" height="900">Beispiel für eine Kachelung eines Musters in Canvas.</canvas>
现在我想用它创建某种网格,它应该看起来像这样
我怎样才能做到这一点?
解决方案
最好的方法是使用两个 for 循环来遍历 x 和 y 值!您可以用这些循环包围绘制文本的部分,并使用不断变化的 x 和 y 值而不是硬编码的值。
async function draw() {
var canvas = document.getElementById('canvas1')
var ctx = canvas.getContext("2d");
var canvas = ctx.createImageData(500, 300);
ctx.fillStyle = "#7289DA";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Select the color of the stroke
ctx.strokeStyle = '#74037b';
// Draw a rectangle with the dimensions of the entire canvas
ctx.strokeRect(0, 0, canvas.width, canvas.height);
ctx.font = 'bold 70px sans-serif';
ctx.fillStyle = '#23272A';
// Select the style that will be used to fill the text in
for (var x = 0; x < canvas.width; x += 100 ) { // 100 is the width
for (var y = 0; y < canvas.height; y += 70) { // 70 is the height
ctx.save();
ctx.translate(x, y); // offset the text
ctx.rotate(1.7*Math.PI);
ctx.fillText('Text', -70, 300);
ctx.restore();
// Actually fill the text with a solid color
}
}
}
ctx.translate(x, y)
使用而不是使用的原因ctx.fillText('Text', x - 70, y + 300)
是因为使用fillText
会以一定角度移动网格,而不是仅仅旋转字母。
推荐阅读
- c++ - 我们可以在没有模板的情况下使用 C++ 关键字“typename”吗?
- laravel - laravel Maatwebsite 验证总和多列
- java - 使用`merger()`的spring-kafka-test中的ClassCastException
- r - 有没有一种简单的方法可以将参数添加到插入符号模型中?
- sql - 比较两个数字字符串并找出唯一值
- ruby-on-rails - 当 prerender 设置为 true 时 React on Rails 错误异常
- javascript - 使用 javascript async/await 检查图像 url
- node.js - 使用 OpenStreetMap/Nominatim 的错误 Nodejs 地理编码
- python - Tensorflow 2.0 Conv3D input_shape 问题
- python-3.x - 有没有办法pairplots可以包含“对象”dtypes变量?