【问题标题】:How to draw image by given coordinate on Canvas?如何在画布上通过给定坐标绘制图像?
【发布时间】:2017-05-20 21:21:40
【问题描述】:

我尝试根据需要将图片放置在分配的坐标上, 但是我不能画出的形状和角度都没有匹配和纠正,只有左上角匹配

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>

谁能告诉我怎么画出正确的角度?

【问题讨论】:

标签: javascript html image html5-canvas


【解决方案1】:

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

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

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();

然后您可以从图像中创建一个图案并将其设置为填充样式

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

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

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

最后你可以使用图案来填充形状:

ctx.fill();

【讨论】:

  • 除非模式适用于整个上下文区域,而不是路径一......这不起作用。
  • 然后它只会裁剪图像,为此有一个clip 方法。
  • 是的,图像被裁剪了..我需要显示整个图像而不裁剪.. :(
  • @Jason 我说这只是一个临时解决方案。顺便说一句,这个问题将被关闭,kalido 发布的内容应该可以解决您的问题
猜你喜欢
  • 1970-01-01
  • 2022-10-23
  • 2017-12-11
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多