我是织物js的初学者。我想在具有背景图像的画布上绘制一个矩形。用户在画布上向下鼠标时第一次进行协调,然后用户鼠标向上然后再次按下鼠标时,应在这些点之间绘制矩形,这些点是左上角点和右下角点。我很困惑如何做到这一点。
我正在分享我用来绘制画布和设置背景图像的代码,它也可以绘制和排列。
<html lang="en" >
<head>
<meta charset="utf-8" />
<title>HTML5 canvas - Image color picker | Script Tutorials</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js" ></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="column1">
<canvas id="panel" width="700" height="350"></canvas>
</div>
<div style="clear:both;"></div>
</div>
</body>
<script>
(function() {
var canvas = new fabric.Canvas('panel', { selection: false });
var line, isDown;
canvas.on('mouse:down', function(o){
isDown = true;
var pointer = canvas.getPointer(o.e);
var points = [ pointer.x, pointer.y, pointer.x, pointer.y ];
console.log(points);
line = new fabric.Line(points, {
strokeWidth: 5,
fill: 'red',
stroke: 'red',
originX: 'center',
originY: 'center'
});
canvas.add(line);
});
canvas.on('mouse:move', function(o){
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
line.set({ x2: pointer.x, y2: pointer.y });
canvas.renderAll();
});
canvas.on('mouse:up', function(o){
isDown = false;
});
fabric.Image.fromURL('fedex.jpg', function (img) {
canvas.add(img.set({
width: 700,
height:350,
left: 350,
top: 175,
selectable: false,
}));
});
})();
</script>
答案 0 :(得分:2)
修改代码如下:
(function() {
var canvas = new fabric.Canvas('panel');
var line, isDown, startPosition={}, rect,drawingMode=true;
canvas.on('mouse:down', function(event){
if (!drawingMode) return;
isDown = true;
console.log(event.e.clientX,event.e.clientY);
startPosition.x=event.e.clientX;
startPosition.y=event.e.clientY;
console.log(startPosition);
rect=new fabric.Rect({
left:event.e.clientX,
top:event.e.clientY,
width:0,
height:0,
stroke:'red',
strokeWidth:3,
fill:''
});
canvas.add(rect);
});
canvas.on('mouse:move', function(event){
if (!isDown || !drawingMode) return;
rect.setWidth(Math.abs( event.e.clientX-startPosition.x ));
rect.setHeight(Math.abs( event.e.clientY -startPosition.y ));
canvas.renderAll();
});
canvas.on('mouse:up', function(){
isDown = false;
canvas.add(rect);
});
canvas.on('object:selected', function(){
drawingMode = false;
});
canvas.on('object:selected', function(){
drawingMode = false;
});
canvas.on('selection:cleared', function(){
drawingMode = true;
});
})();
这将用鼠标绘制矩形 See in Fiddle