gpt4 book ai didi

html - 用鼠标绘制矩形并在 mouseup 上填充颜色

转载 作者:行者123 更新时间:2023-12-05 08:23:08 25 4
gpt4 key购买 nike

我正在使用 Konva 库绘制 Canvas 并将图像拖到 Canvas 上

我的问题是如何使用 Konva 选择 Canvas 的一部分并为所选部分填充颜色

1) 用户通过拖动鼠标选择一个部分2) 给选中的部分填上自己想要的颜色

最佳答案

填充部分 Canvas 的唯一方法是使用形状。

这个片段应该让你继续。

要选择填充颜色,您需要在 mouseup 事件中打开某种自定义颜色选择过程。

// Set up the canvas and shapes
var s1 = new Konva.Stage({container: 'container1', width: 300, height: 200});
var layer1 = new Konva.Layer({draggable: false});
s1.add(layer1);

// draw a background rect to catch events.
var r1 = new Konva.Rect({x: 0, y: 0, width: 300, height: 200, fill: 'gold' })
layer1.add(r1)

// draw a rectangle to be used as the rubber area
var r2 = new Konva.Rect({x: 0, y: 0, width: 0, height: 0, stroke: 'red', dash: [2,2]})
r2.listening(false); // stop r2 catching our mouse events.
layer1.add(r2)

s1.draw() // First draw of canvas.
var posStart;
var posNow;
var mode = '';
function startDrag(posIn){
posStart = {x: posIn.x, y: posIn.y};
posNow = {x: posIn.x, y: posIn.y};
}

function updateDrag(posIn){

// update rubber rect position
posNow = {x: posIn.x, y: posIn.y};
var posRect = reverse(posStart,posNow);
r2.x(posRect.x1);
r2.y(posRect.y1);
r2.width(posRect.x2 - posRect.x1);
r2.height(posRect.y2 - posRect.y1);
r2.visible(true);

s1.draw(); // redraw any changes.

}

// start the rubber drawing on mouse down.
r1.on('mousedown', function(e){
mode = 'drawing';
startDrag({x: e.evt.layerX, y: e.evt.layerY})
})

// update the rubber rect on mouse move - note use of 'mode' var to avoid drawing after mouse released.
r1.on('mousemove', function(e){
if (mode === 'drawing'){
updateDrag({x: e.evt.layerX, y: e.evt.layerY})
}
})

// here we create the new rect using the location and dimensions of the drawing rect.
r1.on('mouseup', function(e){
mode = '';
r2.visible(false);
var newRect = new Konva.Rect({
x: r2.x(),
y: r2.y(),
width: r2.width(),
height: r2.height(),
fill: 'red',
listening: false
})
layer1.add(newRect);
s1.draw();
})


// reverse co-ords if user drags left / up
function reverse(r1, r2){
var r1x = r1.x, r1y = r1.y, r2x = r2.x, r2y = r2.y, d;
if (r1x > r2x ){
d = Math.abs(r1x - r2x);
r1x = r2x; r2x = r1x + d;
}
if (r1y > r2y ){
d = Math.abs(r1y - r2y);
r1y = r2y; r2y = r1y + d;
}
return ({x1: r1x, y1: r1y, x2: r2x, y2: r2y}); // return the corrected rect.
}
p
{
padding: 4px;

}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<p>Click & drag on the background to draw a rectangle and fill it.
</p>
<div id='container1' style="display: inline-block; width: 300px, height: 200px; background-color: silver; overflow: hidden; position: relative;"></div>

关于html - 用鼠标绘制矩形并在 mouseup 上填充颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49758261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com