我正在开发绘画应用程序。当我将绘画板放置在屏幕的左侧时,就可以正确绘制。但是,当我将其放置在屏幕的右侧时,鼠标不会在其所处的位置绘制,而是像在其右侧100 px处那样绘制。我开发了一个拖动功能,该功能使我可以将绘画应用程序的窗口拖动到屏幕上的不同位置。我正在使用香草Javascript和自定义元素。
const template = document.createElement('template')
template.innerHTML = `
<head>
<link rel="stylesheet" href="../css/paint-board.css">
</head>
<div id="board">
<div class="navbar">
<img id="pic" src="../image/tools.png" alt="paint" />
<img id="close" src="../image/error.png" alt="close window" />
</div>
<div id="bucketDiv" class="colour">
<img id="bucket" src="../image/paint-bucket.png" alt="bucket" />
</div>
</div>
<div id="paint">
<canvas id="canvasDrawing">
</canvas>
</div>
</div>
`
export class PaintBoard extends window.HTMLElement {
constructor () {
super()
this.attachShadow({ mode: 'open' })
this.shadowRoot.appendChild(template.content.cloneNode(true))
this.x = 0
this.y = 0
window.colour = 'black'
const canvas = this.shadowRoot.querySelector('#canvasDrawing')
window.ctx = canvas.getContext('2d')
}
connectedCallback () {
this.initialize()
this.closeWindow()
this.changeColour()
this.changeLineWidth()
this.changeBackground()
}
closeWindow () {
const close = this.shadowRoot.querySelector('#board')
close.addEventListener('click', event => {
if (event.target === this.shadowRoot.querySelector('#close')) {
close.classList.add('removed')
}
})
}
// intialize drawing on the board
initialize () {
const paintingBoard = this.shadowRoot.querySelector('#paint')
this.size()
paintingBoard.addEventListener('mousemove', event => {
event.stopImmediatePropagation()
this.draw(event)
})
paintingBoard.addEventListener('mousedown', event => {
event.stopImmediatePropagation()
this.setPosition(event)
})
paintingBoard.addEventListener('mouseenter', event => {
this.setPosition(event)
})
dragElement(this.shadowRoot.querySelector('#board'))
}
draw (e) {
if (e.buttons !== 1) return // if mouse is pressed.....
window.ctx.beginPath() // begin the drawing path
window.ctx.lineCap = 'round' // rounded end cap
window.ctx.strokeStyle = window.colour // hex color of line
window.ctx.moveTo(this.x, this.y) // from position
this.x = e.clientX
this.y = e.clientY
window.ctx.lineTo(this.x, this.y) // to position
window.ctx.stroke() // draw it!
}
// size canvas
size () {
window.ctx.canvas.width = 750
window.ctx.canvas.height = 510
}
// new position from mouse events
setPosition (e) {
this.x = e.clientX
this.y = e.clientY
}