如何保存html画布,然后重新加载,而不会失去形状? [英] How can I save html canvas and then reload it without loosing the shapes?
问题描述
我有一个html5画布,用户可以在其中添加图形。形状有各种各样的行为 - 他们可以调整大小,他们可以移动等
我需要保存它,所以我可以重新加载以后(用户添加的形状,保存,关闭浏览器,当他重新打开浏览器,他应该得到与他之前保存的形状相同的画布,他应该能够移动/调整现有形状并添加新的形状)
toDataURL是不适合我,因为它将所有的形状的画布转换为图像,所以所有现有的形状丢失。
有一些方法可以保存画布或上下文作为db的对象,然后重新加载它。
p>也许你可以在 JSON
对象中存储每个形状的属性,并将其存储在 localStorage
到DB。这样的:
var ShapeData = {shapes:[]}
for(var i = 0; i< ; shapes.length; i ++){
var newShape = {
type:shapes [i] .getType(),
x:shapes [i] .getX b $ by:shapes [i] .getY(),
w:shapes [i] .getWidth(),
h:shapes [i] .getHeight(),
rot:shapes [i ] .getRotation()
}
ShapeData.shapes [i] = newShape;
}
var toTheDatabase = JSON.stringify(ShapeData);
看起来像这样:
var ShapeData = {
shapes:[{
type:square,
x:10,
y:40,
w:2,
h:90,
rot:140
}
type:circle,
x:60,
y:100,
w:2,
h:90,
rot:0
}]
}
I have an html5 canvas to which user can add shapes. shapes have all kind of behaviors - they are resizable, they can be moved around, etc. I need to save it, so I can reload later (user added shapes,saved, closed the browser. when he reopens the browser, he should get the same canvas with the shapes as he saved them before. he should be able to move/resize the exisiting shapes and to add new ones)
toDataURL is not good for me, because it converts canvas with all the shapes to an image, so all the existing shapes are lost. Is there some way to save the canvas or maybe the context as an object to the db and reload it later?
解决方案Perhaps you could store the attributes of each shape in a
JSON
object, and store that inlocalStorage
or save it to the DB. Something like this:var ShapeData = {shapes:[]} for(var i = 0; i < shapes.length; i++) { var newShape = { type : shapes[i].getType(), x : shapes[i].getX(), y : shapes[i].getY(), w : shapes[i].getWidth(), h : shapes[i].getHeight(), rot : shapes[i].getRotation() } ShapeData.shapes[i] = newShape; } var toTheDatabase = JSON.stringify(ShapeData);
Would look like this:
var ShapeData = { "shapes" : [{ "type":"square", "x":"10", "y":"40", "w":"2", "h":"90", "rot":"140" },{ "type":"circle", "x":"60", "y":"100", "w":"2", "h":"90", "rot":"0" }] }
这篇关于如何保存html画布,然后重新加载,而不会失去形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!