如何在Canvas上通过给定坐标绘制图像? [英] How to draw image by given coordinate on Canvas?

查看:2292
本文介绍了如何在Canvas上通过给定坐标绘制图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试根据需要在分配的坐标上放置图片,
但我能做什么绘制形状和角度都没有匹配和纠正,只有左上角匹配

I experimented to place pictures on an allocated coordinate as required, but what I can draw neither shape and angle was matched and corrected, only the top left matches

var _width, _height;
var img = new Image();
var img2 = new Image(),
    img2Widht = 0,
    img2Height = 0;

img.src = "http://production.manboker.com/share/1.jpg";
var canvas = document.getElementById("canvas");
img.onload = function() {
  canvas.width = _width = this.width;
  canvas.height = _height = this.height;
  img2.src = "http://production.manboker.com/share/2.png";
  img2.onload = function() {
    img2Widht = coor['rightTop'][0] - coor['leftTop'][0];
    img2Height = coor['leftBottom'][1] - coor['leftTop'][1];
    step1();
  }
}
var coor = {
  leftTop: ["92", "569"],
  rightTop: ["672", "569"],
  leftBottom: ["109", "1437"],
  rightBottom: ["723", "1437"]
}

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

function step1() {
  ctx.clearRect(0, 0, _width, _height);
  ctx.globalCompositeOperation = 'source-over';
  ctx.drawImage(img,0,0);
  //ctx.globalCompositeOperation = "multiply";
  step2();
}

function step2() {
  ctx.drawImage(img2, 92,569,img2Widht,img2Height);
}

* {
  padding: 0;
  margin: 0;
}
html,
body {
  position: relative;
  overflow: hidden;
  height: 100%;
  width:100%;
}

<canvas id="canvas" style="position:absolute;"></canvas>

谁能告诉我如何以正确的角度绘制它?

Can anyone tell me how to draw it with correct angle?

推荐答案

我将此解决方案作为临时解决方案发布,如果我能找到以正确的方式旋转图像的东西,那么我将其作为新答案发布。

I post this solution as a temporary one, if I can come up something that rotates the image in the right way then I post it besides this as a new answer.

使用上下文的beginPath和lineTo函数,您可以创建形状:

Using the context's beginPath and lineTo functions you can create a shape:

ctx.beginPath();
ctx.lineTo(coor.leftTop[0], coor.leftTop[1]);
ctx.lineTo(coor.rightTop[0], coor.rightTop[1]);
ctx.lineTo(coor.rightBottom[0], coor.rightBottom[1]);
ctx.lineTo(coor.leftBottom[0], coor.leftBottom[1]);
ctx.closePath();

然后你可以从图像中创建一个模式并将其设置为fillstyle

Then you can create a pattern from the image and set it as the fillstyle

var pattern = ctx.createPatter(img2, "repeat");
ctx.fillStyle = pattern;

然后翻译上下文,使模式从正确的位置开始(感谢@Kalido fir指出这一点):

Then translate the context so the pattern starts at the right position (thanks for @Kalido fir pointing this out):

ctx.restore();  // set back the context from the previous try
ctx.save();
ctx.translate(coors.leftTop[0], coors.leftTop[1]);

最后你可以使用这种模式来填充形状:

And lastly you can use the pattern to fill the shape:

ctx.fill();

这篇关于如何在Canvas上通过给定坐标绘制图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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