如何在JavaScript画布FillingStyle中转换图像模式? [英] How to transform the image pattern in JavaScript canvas fillingStyle?

查看:65
本文介绍了如何在JavaScript画布FillingStyle中转换图像模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用JavaScript开发2D图形库,现在我坚持使用背景纹理转换问题.

I'm currently developing a 2D graphic library in JavaScript, and now I'm sticking with the background texture transforming problems.

我想将画布上下文( CanvasRenderingContext2D )的背景纹理(属性 fillStyle )设置为图像( CanvasPattern ).将图像分配给 fillStyle 很容易.但是唯一的问题是,图像实际上无法平移,缩放或倾斜.

I want to set the background texture (property fillStyle) of a canvas context (CanvasRenderingContext2D) to an image (CanvasPattern). It's easy to assign an image to the fillStyle. But the only problem is that, the image can't actually be translated, scaled nor skewed.

我已经查看了MDN,它说有一个名为 setTransform()的原型.使用此API,您可以通过 SVGMatrix 转换图像,这似乎有点烦人.不仅必须创建一个冗余的< svg> 元素,它还是一个实验性的API,并且不能在Google Chrome中工作.

I've looked up MDN, it says there's a prototype called setTransform(). With this API you can transform the image by an SVGMatrix, that seems a little annoying. Not only you'd have to create an redundant <svg> element, it's also an experimental API, and it CAN'T work in Google Chrome.

用常规方法解决是不可能的.有任何"hacky"方法可以做到这一点吗?

It's just impossible to solve using a regular way. Is there any 'hacky' ways to do this?

推荐答案

首先绘制路径,然后设置变换.该路径将保持填充变换时的位置.

First draw the path then set the transform.The path stays where it was while the fill is transformed.

该示例在两个框内旋转图案.

The example rotates the pattern inside two boxes.

const ctx = canvas.getContext('2d');
var pattern;

const img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = () =>  pattern = ctx.createPattern(img, 'repeat');



 requestAnimationFrame(mainLoop);
 function mainLoop(time){
     ctx.setTransform(1,0,0,1,0,0);
     ctx.clearRect(0,0,canvas.width,canvas.height);

     ctx.fillStyle = pattern;

     ctx.beginPath();
     ctx.setTransform(1,0,0,1,0,0);  
     ctx.rect(100,100,200,200); // create the path for rectangle
     ctx.setTransform(1,0,0,1,300,200);  // Set the transform for the pattern
     ctx.rotate(time / 1000);
     ctx.fill();


     ctx.beginPath();
     ctx.setTransform(1,0,0,1,0,0);
     ctx.rect(150,0,100,400); // create the path for the rectangle
     ctx.setTransform(0.2,0,0,0.2,150,200); // Set the transform for the pattern
     ctx.rotate(-time / 1000);
     ctx.fill();

     requestAnimationFrame(mainLoop);
 }

<canvas id="canvas" width="400" height="400" style="border:2px solid black;"></canvas>

这篇关于如何在JavaScript画布FillingStyle中转换图像模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆