鼠标在画布上跟随的图像

时间:2018-07-18 13:47:10

标签: javascript html5-canvas

我想让图像跟随鼠标围绕画布,这非常简单,但是要注意的是,我希望画布以屏幕分辨率进行更改(使用CSS设置为70vw)。

当分辨率降低并且窗口变小时,这意味着使用常规的clientX方法无效。 到目前为止,我的代码是:

var mouseX = e.clientX/document.documentElement.clientWidth * 1920;
var mouseY = e.clientY/document.documentElement.clientHeight * 943;

这将尝试将用户clientX转换为1920x1080显示器上的值。 但是,这并不是很准确,即使在1920x1080显示器上也无法很好地工作。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我从对create a full screen canvas的回答中摘录了片段。

我为鼠标移动添加了它:

let User = { x: 0, y: 0 };

//controles if the mouse is moving
window.addEventListener(
    "mousemove",
    e => {
        User.x = e.clientX;
        User.y = e.clientY;
    },
    false
);

取消注释:cvs.ctx.drawImage(image, User.x, User.y);函数中的ShowImage()在鼠标的x和y位置绘制图像。
注意替换图像源的路径:image.src = "Your/Path/To/Image.png";

/**
 * @author RensvWalstijn. GitHub: https://github.com/RensvWalstijn
 * Sets the canvas properties.
 * @param {object} Cvs Give the html canvas Id.
 * @param {boolean} Fullscreen Change the canvas fullscreen default false.
 * @param {string} Dimension Change the canvas dimension default "2d".
 * @return {object}
 */
function NewCanvas(cvs, fullscreen, dimension) {
    if (!dimension) dimension = "2d";
    var ctx = cvs.getContext(dimension);
    if (fullscreen) {
        cvs.style.position = "fixed";
        cvs.style.left = cvs.x = 0;
        cvs.style.top = cvs.y = 0;
    } else {
        var rect = cvs.getBoundingClientRect();
        cvs.x = rect.left;
        cvs.y = rect.top;
    }
    cvs.ctx = ctx;
    cvs.dimension = dimension;
    cvs.fullscreen = fullscreen;
    return cvs;
}

/**
 * @author RensvWalstijn. GitHub: https://github.com/RensvWalstijn
 * Updates the canvas width and hight.
 * @param {object} Cvs NewCanvas() object.
 * @param {boolean} Clear Change the canvas clear default true.
 */
function UpdateCvs(cvs) {
    if (cvs.fullscreen) {
        //if the width is not the same resize the canvas width
        if (window.innerWidth != cvs.width) {
            cvs.width = window.innerWidth;
        }
        //if the height is not the same resize the canvas height
        if (window.innerHeight != cvs.height) {
            cvs.height = window.innerHeight;
        }
    } else {
        let rect = cvs.getBoundingClientRect();
        cvs.x = rect.left;
        cvs.y = rect.top;
    }
}

function ClearCvs(cvs) {
    if (cvs.dimension == "2d")
        // set fillRect to clearRect to clear all of the canvas
        // fillRect is used here to show the full canvas
        cvs.ctx.fillRect(0, 0, cvs.width, cvs.height);
}

/**
 * @author RensvWalstijn. GitHub: https://github.com/RensvWalstijn
 * get html element by id.
 * @param {string} id give the html element id.
 * @return {object} document.getElementById(id);
 */
function GetId(id) { return document.getElementById(id) }

// To create your canvas object.
var canvas = NewCanvas(GetId("yourCanvasId"), true);

// If you want to update your canvas size use this:
window.addEventListener("resize", function() {
    UpdateCvs(canvas);
});

let User = { x: 0, y: 0 };

//controles if the mouse is moving
window.addEventListener(
  "mousemove",
  e => {
    User.x = e.clientX;
    User.y = e.clientY;
  },
  false
);

// Set it to current width
UpdateCvs(canvas);
ClearCvs(canvas);

// create an image
let image = new Image();
image.src = "Your/Path/To/Image.png";

function ShowImage(cvs) {
    // Use this line to draw your image.
    // cvs.ctx.drawImage(image, User.x, User.y);
    
    // Shows where your image will be drawn.
    cvs.ctx.clearRect(User.x, User.y, 100, 100);
}

function Update() {
    ClearCvs(canvas);
    ShowImage(canvas);
    // keeps it looping
    window.requestAnimationFrame(Update)
}

// Init the loop
Update();
<canvas id="yourCanvasId"></canvas>

答案 1 :(得分:0)

您无法以您认为的方式使用CSS缩放画布。画布基本上是一种更高级的图像。通过CSS缩放画布只会像缩放图像一样拉伸画布。要更改画布heightwidth,您需要在代码中或通过代码更改其heightwidth属性。这样会将画布实际更改为所需的尺寸,而无需缩放和/或拉伸。

话虽如此,我们可以使用它来监视窗口大小的更改,并在窗口更改时调整画布的大小。

window.addEventListener('resize', e => {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
})

通过一些基本的数学运算,我们可以计算出70%的宽度,它将像这样

window.addEventListener('resize', e => {
  canvas.width = window.innerWidth * 0.7
  canvas.height = window.innerHeight
})

我们下一步要做的就是获取鼠标在画布上的局部位置,可以使用mousePosition - canvasOffset这样

let x = e.clientX - canvas.offsetLeft
let y = e.clientY - canvas.offsetTop

说完一切,我们最终得到这样的结果(要在运行中查看它,请运行运行,然后单击Full Page,您将看到画布的调整大小):

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

// Set the inital height and width of the canvas
canvas.width = window.innerWidth
canvas.height = window.innerHeight

canvas.addEventListener('mousemove', e => {
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // Get the local x/y coordinates of the mouse on the canvas
  let x = e.clientX - canvas.offsetLeft
  let y = e.clientY - canvas.offsetTop

  // Draw a dot where the mouse is
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'white';
  ctx.fill();
})

// Update the height and width when the window size changes
window.addEventListener('resize', e => {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
})
body {
  padding: 0;
  margin: 0;
}

canvas {
  background-color: black;
  display: block;
}
<canvas></canvas>

在下面的示例中,我们使用的画布是屏幕的宽度和高度70%,并使用CSS将其居中。但是,我们永远不要将height/widthcss接触,因为它会弄乱画布的坐标系。这部分是使用JavaScript完成的。​​

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

// Set the inital height and width of the canvas
canvas.width = window.innerWidth * 0.7
canvas.height = window.innerHeight * 0.7

canvas.addEventListener('mousemove', e => {
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // Get the local x/y coordinates of the mouse on the canvas
  let x = e.clientX - canvas.offsetLeft
  let y = e.clientY - canvas.offsetTop

  // Draw a dot where the mouse is
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'white';
  ctx.fill();
})

// Update the height and width when the window size changes
window.addEventListener('resize', e => {
  canvas.width = window.innerWidth * 0.7
  canvas.height = window.innerHeight * 0.7
})
body {
  padding: 0;
  margin: 0;
}

canvas {
  background-color: black;
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  margin: auto;
}
<canvas></canvas>