gpt4 book ai didi

javascript - 如何使用 JavaScript 在 Canvas 上手绘?

转载 作者:行者123 更新时间:2023-12-03 01:34:27 25 4
gpt4 key购买 nike

问题

如何在 Canvas 元素上自由绘制(使用鼠标/手指),就像用铅笔进行绘画一样?

关于这个问题

想在canvas上实现徒手画的问题有很多:

所以我认为提出一个引用问题是个好主意,其中每个答案都是社区 wiki,并且包含对一个 JavaScript 库/纯 JavaScript 如何在 Canvas 上绘画的解释。

答案结构

答案应该是社区 wiki 并使用以下模板:

## [Name of library](Link to project page)
### Simple example
A basic, complete example. That means it has to contain HTML
and JavaScript. You can start with this:

<!DOCTYPE html>
<html>
<head>
<title>Simple example</title>
<script type='text/javascript' src='http://cdnjs.com/[your library]'></script>
<style type='text/css'>
#sheet {
border:1px solid black;
}
</style>
<script type='text/javascript'>
window.onload=function(){
// TODO: Adjust
}
</script>
</head>
<body>
<canvas id="sheet" width="400" height="400"></canvas>
</body>
</html>

If possible, this example should work with both, mouse and touch events.

[JSFiddle](Link to code on jsfiddle.net)

This solution works with:

<!-- Please test it the following way: Write "Hello World"
Problems that you test this way are:
* Does it work at all?
* Are lines separated?
* Does it get slow when you write too much?
-->

* Desktop computers:
* [Browser + Version list]
* Touch devices:
* [Browser + Version list] on [Device name]

### Import / Export
Some explanations how to import / export user drawn images.

### Line smoothing
Explanations about how to manipulate the line the user draws.
This can include:
* Bézier curves
* Controlling thickness of lines

最佳答案

Fabric.js

<!DOCTYPE html>
<html>
<head>
<title>Simple example</title>
<script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js'></script>
<style type='text/css'>
#sheet {
border:1px solid black;
}
</style>
<script type='text/javascript'>
window.onload=function(){
var canvas = new fabric.Canvas('sheet');
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 5;
canvas.freeDrawingBrush.color = "#ff0000";
}
</script>
</head>
<body>
<canvas id="sheet" width="400" height="400"></canvas>
</body>
</html>

JSFiddle -Demo

  • 线条的宽度可以通过canvas.freeDrawingBrush.width控制。
  • 线条的颜色可以通过canvas.freeDrawingBrush.color控制。

此解决方案适用于:

  • 台式电脑:
    • Chrome 33
    • 火狐28
  • 触摸设备:
    • Nexus 4 上的 Chrome 34
    • Nexus 4 上的 Opera 20
    • Nexus 4 上的 Firefox 28

导入/导出

只能通过序列化整个 Canvas 来实现,请参阅Tutorial

线条平滑

自动完成,似乎无法停用它。

关于javascript - 如何使用 JavaScript 在 Canvas 上手绘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22891827/

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