I have an image that covers the entire width and height of a canvas that covers the entire screen. The problem is, when the code is run on a computer with a different resolution (width and height), the image does not adjust to the proper height and width of that screen. It stays the original size that I set it in JS. I'm very new to JavaScript, so any help I could get to this image to resize on different resolutions would be amazing. Thanks!
//Global Canvas
var canvas = document.querySelector('.canvas1');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
//Functions
function load_image1() {
"use strict";
var base_image;
base_image = new Image();
base_image.src = ['https://postimg.cc/tnGDb1vD'];
base_image.onload = function(){
c.drawImage(base_image, (window.innerWidth - 1700), -100, 1920, 1080);
};
}
#charset "utf-8";
/* CSS Document */
body {
margin: 0;
}
.canvas1 {
margin: 0;
display: block;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sylvanas</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<canvas class="canvas1">
</canvas>
<!--<canvas class="canvas2">
</canvas>-->
<script src="script.js"></script>
</body>
</html>
You can adjust some c.drawImage() params to get what you're after using some window properties.
Edit: As pointed out in a comment below I added some additional code to listen for a window resize which will adjust the dimensions of the canvas image as needed. This solution does flash a bit on my screen when resizing so there is a potential drawback.
c.drawImage(base_image, 0, 0, canvas.width, canvas.height);
JSFiddle: http://jsfiddle.net/gucr5m1b/4/
var canvas = document.querySelector('.canvas1');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
function load_image1() {
"use strict";
var base_image = new Image();
base_image.src = ['http://i.imgur.com/8rmMZI3.jpg'];
base_image.onload = function() {
c.drawImage(base_image, 0, 0, canvas.width, canvas.height);
};
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
load_image1();
}
function startCanvas() {
window.addEventListener('resize', resizeCanvas, false);
resizeCanvas();
}
startCanvas();
#charset "utf-8";
/* CSS Document */
body {
margin: 0;
}
.canvas1 {
margin: 0;
display: block;
}
<canvas class="canvas1"></canvas>
I am not a real programmer but have done some small projects in JavaScript. I am now working on a small app backing up a scientific poster. The script works, but the cursor (cross) and the other field, both bit maps do not appear before the page is reloaded. Same behavior in several browsers. I found out that the onload function is not run. But the first one img is run. I don't understand why.
I did some googling and found references to the problem but did not really understand it.
Could somebody be so kind and help me?
I made a versjon with only the essential gode:
URL: http://folk.uio.no/gerald/IADMFR2017/test.html
Here is the source:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Increasing clinical relevance in oral radiology through computer-based examination?</title>
<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
<script>
function init() {
var canvas = document.getElementById("canvas");
var stage = new createjs.Stage(canvas);
stage.enableMouseOver();
createjs.Touch.enable( stage );
img = new Image();
img.src = 'images/radiograph.png';
img.onload = function(event) {
var bitmap = new createjs.Bitmap('images/radiograph.png');
bitmap.x = 50;
bitmap.y = 80;
bitmap.on("click", handleMouseEvent);
stage.addChild(bitmap);
stage.update();
}
fieldIm = new Image();
fieldIm.src = 'images/field.png';
var field;
fieldIm.onload = function(event) {
field = new createjs.Bitmap('images/field.png');
field.scaleX=0.9;
field.scaleY=0.9;
field.x=400;
field.y=100;
field.visible = false;
stage.addChild(field);
stage.update();
}
crossIm = new Image();
crossIm.src = 'images/cross.png';
var cross;
crossIm.onload = function(event) {
cross = new createjs.Bitmap('images/cross.png');
cross.scaleX=0.5;
cross.scaleY=0.5;
cross.zIndex = 500;
cross.visible = false;
stage.addChild(cross);
stage.update();
}
stage.update();
function handleMouseEvent(evt) {
cross.x = evt.rawX - 12;
cross.y = evt.rawY - 12;
cross.visible = true;
stage.update();
}
var rect = new createjs.Rectangle(0, 0, 180, 30);
var frg = '#FFFFFF';
var bkg = '#000000';
var container = new createjs.Container();
container.x = 450;
container.y = 500;
var rectShape = new createjs.Shape();
rectShape.graphics.c().f(bkg).dr(0, 0, rect.width, rect.height);
var text = new createjs.Text("Check Result", "30px Arial", "#FFFFFF");
container.addChild(rectShape);
container.addChild(text);
container.on("click", handleToggle);
stage.addChild(container);
stage.update();
function handleToggle(evt) {
field.visible = !field.visible;
if (field.visible) {
text.text="Hide Result";
} else {
text.text="Check Result";
}
stage.update();
}
stage.update();
}
</script>
</head>
<body onload="init()">
<H1>Poster ICDMFR 2017 Clickable task example</H1>
<canvas id="canvas" width="800" height="600"></canvas>
</body>
</html>
I appreciate any help on that.
Greetings
Gerald
http://www.odont.uio.no/english/people/adm/fac/gerald
So the idea is - I want to get the canvas position style to be fixed through js, so I don't get the scroll bars.
The thing is - I can change the style easily with chrome inspector and all works fine, but js refuses to corporate...
function setup() {
//full screen setup
canvas = createCanvas(window.innerWidth*2,window.innerHeight*2);
canStyle = canvas.style;
canvas.style.position = "fixed";
mainWrap = document.getElementById('mainWrap');
canvas.parent(mainWrap);
This is what I get instead :
The html, body and main wrap are 100% , just the way I want it, but the canvas itself is stretched, but not fixed...
I really don't know what I'm doing wrong... Ideas?
The manual chrome inspector edit does the job...
Whole Code
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Sky</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script language="javascript" type="text/javascript" src="libs/p5.js"></script>
<script language="javascript" src="libs/p5.dom.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="star.js"></script>
<style> body {padding: 0; margin: 0;} </style>
</head>
<body>
<div id="mainWrap">
</div>
</body>
</html>
css:
html, body, #mainWrap {
height:100%;
width:100%;
margin:0px;
}
body{
background-color: #222222;
}
JS:
var mainWrap;
var sky = [];
var x;
var y;
var trans = false;
function setup() {
//full screen setup
canvas = createCanvas(window.innerWidth*2,window.innerHeight*2);
canStyle = canvas.style;
canvas.style.position = "fixed";
mainWrap = document.getElementById('mainWrap');
canvas.parent(mainWrap);
for(var i = 0; i < 1; i++){
var star = new Star(i, random(width),random(height), Math.floor(random(1,4)));
sky[i] = star;
console.log(sky[i]);
}
}
function draw() {
background(34,34,34);
x = mouseX;
y = mouseY;
if(trans === false){
translate(x-(width/2),y-(height/2));
}
for (var i=0; i < sky.length; i++){
sky[i].show();
sky[0].fall(0.4,0.3);
}
}
Star obj:
function Star(id,xCord, yCord, parallax) {
this.parrlax = parallax;
this.id = id;
this.x = xCord;
this.y = yCord;
this.r = parallax;
noStroke();
this.show = function(){
fill(255,255,255, random(30*this.parrlax,this.parrlax*40));
ellipse(this.x, this.y, this.r*2, this.r*2);
}
this.fall = function(xMove, yMove) {
this.x += xMove;
this.y += yMove;
fill(100,100,100);
ellipse(this.x,this.y,3,3);
}
}
Assuming createCanvas is a method form P5.js, you need to access the underlying DOM element of the created canvas:
canvas = createCanvas(window.innerWidth*2,window.innerHeight*2);
// canvas here refers to an instance of P5 canvas, not a HTML5 canvas element,
// but the real DOM canvas is available as either .canvas or .elt
canvas.elt.style.position = "fixed";
Question
How do I draw free (using my mouse / fingers) on a canvas element like you can do it in paint with a pencil?
About this question
There are a lot of questions that want to achieve free hand drawing on canvas:
draw by mouse with HTML5 Canvas
KineticJS - Draw free with mouse
Free drawing on canvas using fabric.js
Sketching with JS
Paint canvas not working properly
Mouse position on canvas painting
Implementing smooth sketching and drawing on the element
So I thought it would be a good idea to make a reference question, where every answer is community wiki and contains a explanation for exactly one JavaScript library / pure JavaScript how to do paint on canvas.
Structure of answers
The answers should be community wiki and use the following template:
## [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
The width of the lines can be controlled with canvas.freeDrawingBrush.width.
The color of the lines can be controlled with canvas.freeDrawingBrush.color.
This solution works with:
Desktop computers:
Chrome 33
Firefox 28
Touch devices:
Chrome 34 on Nexus 4
Opera 20 on Nexus 4
Firefox 28 on Nexus 4
Import / Export
Is only possible by serializing the complete canvas, see Tutorial
Line smoothing
Is done automatically and it seems not to be possible to deactivate it.
Plain JavaScript
Simple example
<!DOCTYPE html>
<html>
<head>
<title>Simple example</title>
<style type='text/css'>
#sheet {
border:1px solid black;
}
</style>
</head>
<body>
<canvas id="sheet" width="400" height="400"></canvas>
<script type='text/javascript'>
/*jslint browser:true */
"use strict";
var context = document.getElementById('sheet').getContext("2d");
var canvas = document.getElementById('sheet');
context = canvas.getContext("2d");
context.strokeStyle = "#ff0000";
context.lineJoin = "round";
context.lineWidth = 5;
var clickX = [];
var clickY = [];
var clickDrag = [];
var paint;
/**
* Add information where the user clicked at.
* #param {number} x
* #param {number} y
* #return {boolean} dragging
*/
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
/**
* Redraw the complete canvas.
*/
function redraw() {
// Clears the canvas
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
for (var i = 0; i < clickX.length; i += 1) {
if (!clickDrag[i] && i == 0) {
context.beginPath();
context.moveTo(clickX[i], clickY[i]);
context.stroke();
} else if (!clickDrag[i] && i > 0) {
context.closePath();
context.beginPath();
context.moveTo(clickX[i], clickY[i]);
context.stroke();
} else {
context.lineTo(clickX[i], clickY[i]);
context.stroke();
}
}
}
/**
* Draw the newly added point.
* #return {void}
*/
function drawNew() {
var i = clickX.length - 1
if (!clickDrag[i]) {
if (clickX.length == 0) {
context.beginPath();
context.moveTo(clickX[i], clickY[i]);
context.stroke();
} else {
context.closePath();
context.beginPath();
context.moveTo(clickX[i], clickY[i]);
context.stroke();
}
} else {
context.lineTo(clickX[i], clickY[i]);
context.stroke();
}
}
function mouseDownEventHandler(e) {
paint = true;
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
if (paint) {
addClick(x, y, false);
drawNew();
}
}
function touchstartEventHandler(e) {
paint = true;
if (paint) {
addClick(e.touches[0].pageX - canvas.offsetLeft, e.touches[0].pageY - canvas.offsetTop, false);
drawNew();
}
}
function mouseUpEventHandler(e) {
context.closePath();
paint = false;
}
function mouseMoveEventHandler(e) {
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
if (paint) {
addClick(x, y, true);
drawNew();
}
}
function touchMoveEventHandler(e) {
if (paint) {
addClick(e.touches[0].pageX - canvas.offsetLeft, e.touches[0].pageY - canvas.offsetTop, true);
drawNew();
}
}
function setUpHandler(isMouseandNotTouch, detectEvent) {
removeRaceHandlers();
if (isMouseandNotTouch) {
canvas.addEventListener('mouseup', mouseUpEventHandler);
canvas.addEventListener('mousemove', mouseMoveEventHandler);
canvas.addEventListener('mousedown', mouseDownEventHandler);
mouseDownEventHandler(detectEvent);
} else {
canvas.addEventListener('touchstart', touchstartEventHandler);
canvas.addEventListener('touchmove', touchMoveEventHandler);
canvas.addEventListener('touchend', mouseUpEventHandler);
touchstartEventHandler(detectEvent);
}
}
function mouseWins(e) {
setUpHandler(true, e);
}
function touchWins(e) {
setUpHandler(false, e);
}
function removeRaceHandlers() {
canvas.removeEventListener('mousedown', mouseWins);
canvas.removeEventListener('touchstart', touchWins);
}
canvas.addEventListener('mousedown', mouseWins);
canvas.addEventListener('touchstart', touchWins);
</script>
</body>
</html>
JSFiddle
The width of the lines can be controlled with context.lineWidth.
The color of the lines can be controlled with strokeStyle.
This solution works with:
Desktop computers:
Chrome 33
Firefox 28
Touch devices:
Firefox 28 on Nexus 4
It does not work with
Touch devices:
Chrome 34 / Opera 20 on Nexus 4 (see issue)
Import / Export
Importing and exporting the image can be done by importing / exporting clickX, clickY and clickDrag.
Line smoothing
Can eventually be done by replacing lineTo() with bezierCurveTo()
Plain JS - ES6
Simple example
Plain Javascript example above has some serious issues: it does not reflect the comments objections, the paint state is redundant, events are not unhooked properly, the redraw() function is not used, it can be simplified a lot and it doesn't work with modern syntax. The fix is here:
var canvas = document.getElementById('sheet'), g = canvas.getContext("2d");
g.strokeStyle = "hsl(208, 100%, 43%)";
g.lineJoin = "round";
g.lineWidth = 1;
g.filter = "blur(1px)";
const
relPos = pt => [pt.pageX - canvas.offsetLeft, pt.pageY - canvas.offsetTop],
drawStart = pt => { with(g) { beginPath(); moveTo.apply(g, pt); stroke(); }},
drawMove = pt => { with(g) { lineTo.apply(g, pt); stroke(); }},
pointerDown = e => drawStart(relPos(e.touches ? e.touches[0] : e)),
pointerMove = e => drawMove(relPos(e.touches ? e.touches[0] : e)),
draw = (method, move, stop) => e => {
if(method=="add") pointerDown(e);
canvas[method+"EventListener"](move, pointerMove);
canvas[method+"EventListener"](stop, g.closePath);
};
canvas.addEventListener("mousedown", draw("add","mousemove","mouseup"));
canvas.addEventListener("touchstart", draw("add","touchmove","touchend"));
canvas.addEventListener("mouseup", draw("remove","mousemove","mouseup"));
canvas.addEventListener("touchend", draw("remove","touchmove","touchend"));
<canvas id="sheet" width="400" height="400" style="border: 1px solid black"></canvas>
Support
It should work everywhere today. I could be further simplified by pointer events, but Safari lacks support for it as of 2021.
Import / Export
For import, use g.drawImage()
g.drawImage(img, 0, 0);
For export, see canvas.toBlob()
function save(blob) {
var fd = new FormData();
fd.append("myFile", blob);
// handle formData to your desire here
}
canvas.toBlob(save,'image/jpeg');
Line smoothing
For antialiasing, See blur() from SVG filters; if you import, don't forget to apply it AFTER the image is imported
context.filter = "blur(1px)";
Paper.js
Simple example
<!DOCTYPE html>
<html>
<head>
<title>Paper.js example</title>
<script type='text/javascript' src='http://paperjs.org/assets/js/paper.js'></script>
<style type='text/css'>
#sheet {
border:1px solid black;
}
</style>
</head>
<body>
<script type="text/paperscript" canvas="sheet">
var path;
function onMouseDown(event) {
// If we produced a path before, deselect it:
if (path) {
path.selected = false;
}
// Create a new path and set its stroke color to black:
path = new Path({
segments: [event.point],
strokeColor: 'black',
strokeWidth: 3
});
}
// While the user drags the mouse, points are added to the path
// at the position of the mouse:
function onMouseDrag(event) {
path.add(event.point);
}
// When the mouse is released, we simplify the path:
function onMouseUp(event) {
path.simplify();
}
</script>
<canvas id="sheet" width="400" height="400"></canvas>
</body>
</html>
JSFiddle
The width of the lines can be controlled with strokeWidth.
The color of the lines can be controlled with strokeColor.
This solution works with:
Desktop computers:
Chrome 33
Import / Export
?
Line smoothing
Line smoothing can be done by adjusting path.simplify();.
EaselJs
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>EaselJS example</title>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/EaselJS/0.7.1/easeljs.min.js"></script>
<script>
var canvas, stage;
var drawingCanvas;
var oldPt;
var oldMidPt;
var color;
var stroke;
var index;
function init() {
if (window.top != window) {
document.getElementById("header").style.display = "none";
}
canvas = document.getElementById("sheet");
index = 0;
//check to see if we are running in a browser with touch support
stage = new createjs.Stage(canvas);
stage.autoClear = false;
stage.enableDOMEvents(true);
createjs.Touch.enable(stage);
createjs.Ticker.setFPS(24);
drawingCanvas = new createjs.Shape();
stage.addEventListener("stagemousedown", handleMouseDown);
stage.addEventListener("stagemouseup", handleMouseUp);
stage.addChild(drawingCanvas);
stage.update();
}
function stop() {}
function handleMouseDown(event) {
color = "#ff0000";
stroke = 5;
oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
oldMidPt = oldPt;
stage.addEventListener("stagemousemove" , handleMouseMove);
}
function handleMouseMove(event) {
var midPt = new createjs.Point(oldPt.x + stage.mouseX>>1, oldPt.y+stage.mouseY>>1);
drawingCanvas.graphics.clear().setStrokeStyle(stroke, 'round', 'round').beginStroke(color).moveTo(midPt.x, midPt.y).curveTo(oldPt.x, oldPt.y, oldMidPt.x, oldMidPt.y);
oldPt.x = stage.mouseX;
oldPt.y = stage.mouseY;
oldMidPt.x = midPt.x;
oldMidPt.y = midPt.y;
stage.update();
}
function handleMouseUp(event) {
stage.removeEventListener("stagemousemove" , handleMouseMove);
}
</script>
</head>
<body onload="init();">
<canvas id="sheet" width="400" height="400"></canvas>
</body>
</html>
Demo
The interesting parts in the documentation are:
EaselJS: A starting point for getting into EaselJS.
Stage Class:
This solution works with:
Desktop computers:
Chrome 33
Firefox 28
Touch devices:
Chrome 34 / Firefox 28 / Opera 20 on Nexus 4
Import / Export
?
Line smoothing
?
Here, try my canvas free drawing and erase.
https://jsfiddle.net/richardcwc/d2gxjdva/
//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
var tooltype = 'draw';
//Mousedown
$(canvas).on('mousedown', function(e) {
last_mousex = mousex = parseInt(e.clientX-canvasx);
last_mousey = mousey = parseInt(e.clientY-canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function(e) {
mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX-canvasx);
mousey = parseInt(e.clientY-canvasy);
if(mousedown) {
ctx.beginPath();
if(tooltype=='draw') {
ctx.globalCompositeOperation = 'source-over';
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
} else {
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = 10;
}
ctx.moveTo(last_mousex,last_mousey);
ctx.lineTo(mousex,mousey);
ctx.lineJoin = ctx.lineCap = 'round';
ctx.stroke();
}
last_mousex = mousex;
last_mousey = mousey;
//Output
$('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
});
//Use draw|erase
use_tool = function(tool) {
tooltype = tool; //update
}
canvas {
cursor: crosshair;
border: 1px solid #000000;
}
<canvas id="canvas" width="800" height="500"></canvas>
<input type="button" value="draw" onclick="use_tool('draw');" />
<input type="button" value="erase" onclick="use_tool('erase');" />
<div id="output"></div>
(Disclaimer: I wrote this library)
Scrawl.js
Simple example
<!DOCTYPE html>
<html>
<head>
<title>Simple example</title>
<style type='text/css'>
#sheet {border:1px solid black;}
</style>
</head>
<body>
<canvas id="sheet" width="400" height="400"></canvas>
<script src="http://scrawl.rikweb.org.uk/js/scrawlCore-min.js"></script>
<script>
var mycode = function(){
//define variables
var myPad = scrawl.pad.sheet,
myCanvas = scrawl.canvas.sheet,
sX, sY, here,
drawing = false,
currentSprite = false,
startDrawing,
endDrawing;
//event listeners
startDrawing = function(e){
drawing = true;
currentSprite = scrawl.newShape({
start: here,
lineCap: 'round',
lineJoin: 'round',
method: 'draw',
lineWidth: 4,
strokeStyle: 'red',
data: 'l0,0 ',
});
sX = here.x;
sY = here.y;
if(e){
e.stopPropagation();
e.preventDefault();
}
};
myCanvas.addEventListener('mousedown', startDrawing, false);
endDrawing = function(e){
if(currentSprite){
currentSprite = false;
}
drawing = false;
if(e){
e.stopPropagation();
e.preventDefault();
}
};
myCanvas.addEventListener('mouseup', endDrawing, false);
//animation object
scrawl.newAnimation({
fn: function(){
//get current mouse position
here = myPad.getMouse();
if(here.active){
if(drawing){
if(here.x !== sX || here.y !== sY){
//extend the line
currentSprite.set({
data: currentSprite.data+' '+(here.x - sX)+','+(here.y - sY),
});
sX = here.x;
sY = here.y;
}
}
}
else{
//stop drawing if mouse leaves canvas area
if(currentSprite){
endDrawing();
}
}
//update display
scrawl.render();
},
});
};
//Scrawl is modular - load additional modules
scrawl.loadModules({
path: 'js/',
modules: ['animation', 'shape'],
callback: function(){
window.addEventListener('load', function(){
scrawl.init(); //start Scrawl
mycode(); //run code
}, false);
},
});
</script>
</body>
</html>
JSFiddle
This solution works with:
recent versions of IE, Chrome, Firefox, Opera (desktop)
(not tested on mobile/touch devices)
Adding touch support
(try adding a dedicated touch library like Hammer.js?)
Import / Export
Scrawl has experimental support for saving and loading JSON strings
tutorial page: load and save
Line smoothing and other sprite manipulations
line data is saved internally as an SVGTiny Path.d value - any algorithm that can take line data in that format and smooth it should work
line attributes - thickness, color, positioning, rotation, etc - can be set, and animated.
I'm using RaphaëlJS for rotating an image forever. You can see the current result here. However, I'm experiencing some performance issues after resizing the browser window many times.
Could it be that new animations are created every time the window is resized while old ones are not removed? If that's the case, how can I stop and remove them? If not the case, any idea about how I could improve the performance?
The code is this:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
background-color: black;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript" src="raphael.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var gearImageSrc = "images/gear.png";
var nikaImageSrc = "images/nika_half.png";
var logoImageSrc = "images/logo_mp.png";
var paper;
var gearImage = new Image();
var nikaImage = new Image();
var logoImage = new Image();
gearImage.src = gearImageSrc;
nikaImage.src = nikaImageSrc;
logoImage.src = logoImageSrc;
showAll = function () {
paper = Raphael(0, 0, canvas.width,canvas.height);
gear = paper.image(gearImageSrc, canvas.width/2 - gearImage.width/4, canvas.height/2 - gearImage.height/3, gearImage.width/2, gearImage.height/2);
nika = paper.image(nikaImageSrc, canvas.width/2 - nikaImage.width/4, canvas.height/2 - nikaImage.height/3, nikaImage.width/2, nikaImage.height/2);
logo = paper.image(logoImageSrc, canvas.width/2 - logoImage.width/4, canvas.height/2 + gearImage.height/6, logoImage.width/1.5, logoImage.height/1.5);
var spin = Raphael.animation({transform: "r-360"}, 10000).repeat(Infinity);
gear.animate(spin);
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
paper.remove();
showAll();
}
window.addEventListener('resize', resizeCanvas, false);
window.onload = function () {
showAll();
}
</script>
</body>
</html>
I might have a solution for it, just let me know if this works:
var spin = Raphael.animation({transform: "...r-360"}, 10000).repeat(Infinity);
You have to add ... in your transform() whenever you want to append to your transform, which you seem to be doing by re-sizing the window.